package com.wuyoucar.controller;

import com.wuyoucar.common.ResultBean;
import com.wuyoucar.entity.TReal;
import com.wuyoucar.entity.TUserinfo;
import com.wuyoucar.mapper.TUserinfoMapper;
import com.wuyoucar.service.TRealService;
import com.wuyoucar.util.CardTextUtil;
import com.wuyoucar.util.IdcardUtil;
import com.wuyoucar.util.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileUploadController {
    @Autowired
    private TRealService tRealService;
    @Autowired
    private TUserinfoMapper tUserinfoMapper;
    // 项目根路径下的目录  -- SpringBoot static 目录相当于是根路径下（SpringBoot 默认）
    public final static String UPLOAD_PATH_PREFIX = "static/uploadFile/";


    @RequestMapping("/upload/{userid}")
    @ResponseBody
    public ResultBean cardText(@RequestParam(value = "img", required = false) MultipartFile img, @PathVariable("userid") Integer userid, HttpServletRequest request) {
        if (img.isEmpty()) {
            //返回选择文件提示
            return new ResultBean(0, "请选择上传文件", "");
        }
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        //构建文件上传所要保存的"文件夹路径"--这里是相对路径，保存到项目根路径的文件夹下
        String realPath = new String("client/src/main/resources/" + UPLOAD_PATH_PREFIX);
//        String format = sdf.format(new Date());
        //存放上传文件的文件夹
        File file = new File(realPath);
        if (!file.isDirectory()) {
            //递归生成文件夹
            file.mkdirs();
        }
        //获取原始的名字  original:最初的，起始的  方法是得到原来的文件名在客户机的文件系统名称
        String oldName = img.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            //构建真实的文件路径
            File newFile = new File(file.getAbsolutePath() + File.separator + newName);
            //转存文件到指定路径，如果文件名重复的话，将会覆盖掉之前的文件,这里是把文件上传到 “绝对路径”
            img.transferTo(newFile);
            //文件保存路径
            String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/uploadFile/" + newName;
            //使用文字识别解析图片内容,判断是否符合身份证文件(param 路径及文件名)
            Map<String, Object> map = CardTextUtil.recognition(realPath + newName);
            String realname = (String) map.get("姓名");
            String sexT = (String) map.get("性别");
            Integer sex = 0;
            sex = sexT.equals("男") ? 0 : 1;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Date birthday = sdf.parse((String) map.get("出生"));//
            String idnumber = (String) map.get("公民身份号码");
            String address = (String) map.get("住址");
            String frontidcard = newName;
            Integer applyerid = userid;
            //判断是否 新增 认证信息还是 修改
            if (tRealService.selReal(userid) == null) {
                //实名认证申请,将身份证信息保存到实名制认证表
                TReal tReal = new TReal(realname, sex, birthday, idnumber, address, frontidcard, applyerid);
                int count = tRealService.addCard(tReal);
                System.out.println(count);
            } else {
                //实名认证申请,将身份证信息保存到实名制认证表
                TReal tReal = new TReal(realname, sex, birthday, idnumber, address, frontidcard, applyerid);
                int count = tRealService.alterReal(tReal);
                System.out.println(count);
            }

            //上传成功返回文件路径(包含文件名),将页面的身份证示范替换成上传的身份证文件
            return new ResultBean(1, "上传成功", newName);
            //将上传的图片名称保存至数据库

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResultBean(0, "请上传正确的居民身份证正面", "");
    }

    @RequestMapping("/save/{userid}")
    public ResultBean save(@PathVariable("userid") Integer userid) {
        //获取身份证图片信息
        String idCard = tRealService.selReal(userid).getIdnumber();
        String name = tRealService.selReal(userid).getRealname();
        //身份证实名查询接口
        if (IdcardUtil.checkIdCard(idCard, name)) {
            Integer applyerid = userid;
            tRealService.real(applyerid);
            int n = tUserinfoMapper.updateIdnumber(new TUserinfo(userid,MD5.MD5(idCard)));
            return new ResultBean(1, "实名认证成功!", 0);
        } else {
            return new ResultBean(0, "实名认证失败!", 0);
        }
    }
}
